package br.com.speedprevweb.dao.impl;

import br.com.speedprevweb.dao.TipoRegimeDao;
import br.com.speedprevweb.model.TipoRegime;
import br.com.speedprevweb.util.HibernateUtil;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class TipoRegimeDaoImpl implements TipoRegimeDao {

  private boolean valid(TipoRegime tipoRegime) {
    if (tipoRegime.getCdTipoRegime().isEmpty()) {
      return false;
    } else {
      return !tipoRegime.getDsTipoRegime().isEmpty();
    }
  }

  @Override
  public void salvar(TipoRegime tipoRegime) {
    Session session = null;
    Transaction t = null;

    try {
      session = HibernateUtil.getSessionFactory().openSession();
      t = session.beginTransaction();
      session.save(tipoRegime);
      t.commit();
    } catch (RuntimeException e) {
      try {
        t.rollback();
      } catch (RuntimeException rbe) {
        //log.error("Não foi possível reverter transação");
        System.out.println("Não foi possível reverter transação");
        throw e;
      }
    } finally {
      if (session != null) {
        session.close();
      }
    }
  }

  @Override
  public void alterar(TipoRegime tipoRegime) {
    Session session = null;
    Transaction t = null;

    try {
      session = HibernateUtil.getSessionFactory().openSession();
      t = session.beginTransaction();
      session.update(tipoRegime);
      t.commit();
    } catch (RuntimeException e) {
      try {
        t.rollback();
      } catch (RuntimeException rbe) {
        System.out.println("Não foi possível reverter transação");
        throw e;
      }
    } finally {
      if (session != null) {
        session.close();
      }
    }
  }

  @Override
  public void excluir(TipoRegime tipoRegime) {
    Session session = null;
    Transaction t = null;

    try {
      session = HibernateUtil.getSessionFactory().openSession();
      t = session.beginTransaction();
      session.delete(tipoRegime);
      t.commit();
    } catch (RuntimeException e) {
      try {
        t.rollback();
      } catch (RuntimeException rbe) {
        System.out.println("Não foi possível reverter transação");
        throw e;
      }
    } finally {
      if (session != null) {
        session.close();
      }
    }
  }

  @Override
  public TipoRegime getTipoRegime(long idTipoRegime) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    return (TipoRegime) session.load(TipoRegime.class, idTipoRegime);
  }

  @Override
  public List<TipoRegime> listarTodos() {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction t = session.beginTransaction();
    List<TipoRegime> lista = session.createQuery("FROM TipoRegime tr order by tr.dsTipoRegime").list();
    t.commit();
    session.close();
    return lista;
  }
}